<template>
	<view class="content">
		<home-vue v-if="selected === 0" :todays="todays" :hots="hots"></home-vue>
		<search-vue v-if="selected === 1" :list="list"></search-vue>
		<message-vue v-if="selected === 2" :users="users" ></message-vue>
		<my-vue v-if="selected === 3" :user="user"></my-vue>
	</view>

	<view class="navigator">
		<view class="home" @click="selected = 0">
			<image src="../../static/home.png" mode="widthFix"></image>
			<text v-if="selected === 0">首页</text>
		</view>
		<view class="search" @click="selected = 1">
			<image src="../../static/search.png" mode="widthFix"></image>
			<text v-if="selected === 1">搜索</text>
		</view>

		<view class="message" @click="selected = 2">
			<image src="../../static/message.png" mode="widthFix"></image>
			<text v-if="selected === 2">消息</text>
		</view>
		<view class="my" @click="selected = 3">
			<image src="../../static/my.png" mode="widthFix"></image>
			<text v-if="selected === 3">我的</text>
		</view>
		<view class="shadow" :style="{ left: move() }"></view>

	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import homeVue from '../../component/home/home.vue';
	import searchVue from '../../component/search/search.vue';
	import messageVue from '../../component/message/message.vue';
	import myVue from '../../component/my/my.vue';
	const selected = ref(0)
	const move = () => {
		const x = selected.value
		let dx = 0
		switch (x) {
			case 0:
				dx = 75;
				break;
			case 1:
				dx = 220;
				break;
			case 2:
				dx = 370;
				break;
			case 3:
				dx = 510;
				break;
		}
		return dx + 'rpx'
	}
	const user = ref({
		avatar: '../../static/image_39.png',
		username: '凤凰花开',
		email: 'igrtedfg@fgggeh2135.com',
		number: '13527668842'
	})
	const todays = ref(uni.getStorageSync('todays'))
	const db = uniCloud.database()
	const hots = ref(uni.getStorageSync('hots'))
	const list = ref(uni.getStorageSync('lists'))
	
	const users = ref(uni.getStorageSync('users'))

	const getUserData = () => {
		uni.showLoading({
			title: '正在加载用户数据……',
			mask: true
		})
		uniCloud.callFunction({
			name: 'findUserById',
			data: {
				id: uni.getStorageSync("userId")
			}
		}).then((res) => {
			console.log(res);
			const newUser = res.result.data[0]
			user.value = {
				_id: newUser._id,
				avatar: newUser.avatar,
				username: newUser.username,
				email: newUser.email,
				number: newUser.number
			}
			uni.setStorageSync('avatar', newUser.avatar)
		}).catch((err) => {
			console.log(err.message);
		}).finally(() => {
			uni.hideLoading()
		})
	}

	const getHomeTodays = () => {
		db.collection('goods')
			.where('status == 2 || status == 6')
			.limit(5)
			.get()
			.then((res) => {
				console.log(res);
				todays.value = res.result.data.map(x => {
					return {
						_id: x._id,
						name: x.name,
						content: x.description,
						value: x.value,
						url: x.image
					}
				});
				uni.setStorageSync('todays', todays.value)
			}).catch((err) => {
				console.log(err.message);
			})
	}

	const getHots = () => {
		db.collection('goods')
			.where('status == 6 || status == 4')
			// .limit(2)
			.get()
			.then(res => {
				console.log(res);
				hots.value = res.result.data.map(x => {
					return {
						_id: x._id,
						name: x.name,
						content: x.description,
						value: x.value,
						url: x.image
					}
				})
				uni.setStorageSync('hots', hots.value)
				console.log(hots.value.length);
			}).catch(err => {
				console.log(`getHots: ${err.message}`);
			})
	}

	const getlists = () => {
		db.collection('goods')
			// .where('status == 6 || status == 4')
			.orderBy('_id desc')
			.limit(6)
			.get()
			.then(res => {
				console.log(res);
				list.value = res.result.data.map(x => {
					return {
						_id: x._id,
						name: x.name,
						content: x.description,
						value: x.value,
						url: x.image
					}
				})
				console.log(list.value.length);
				uni.setStorageSync('lists', list.value)
			}).catch(err => {
				console.log(err.message)
			})
	}
	function timestampToDate(timestamp) {
		var date = new Date(timestamp); 
		const Y = date.getFullYear() + '-';
		const M = date.getMonth() + 1 + '-'
		const D = date.getDate() + ' ';
		const h = String(date.getHours()).padStart(2, '0') + ':';
		const m = String(date.getMinutes()).padStart(2, '0') + ':';
		const s = String(date.getSeconds()).padStart(2, '0');
		return Y+M+D+h+m+s
	}

	const getTalking = async () => {
		const id = uni.getStorageSync("userId");
		const aPromise = db.collection('talking').where(`aid == '${id}'`).field('bid as x, content, time').get();
		const bPromise = db.collection('talking').where(`bid == '${id}'`).field('aid as x, content, time').get();

		// 等待所有查询完成
		Promise.all([aPromise, bPromise]).then(([aResult, bResult]) => {
				const a = aResult.result.data
				const b = bResult.result.data
				const arr = [...a, ...b]
				arr.sort((a, b) => b.time - a.time)
				console.log(arr);
				let uniqueArray = arr.filter((value, index, self) =>
					index === self.findIndex(t => t.x === value.x)
				);
				console.log(uniqueArray);
				const list1 = uniqueArray.map(x => { return `'${x.x}'` }).toString()
				console.log(`[${list1}]`);
				db.collection('user')
					.where(`_id in [${list1}]`)
					.field('username, avatar')
					.get()
					.then(res => {
						console.log(res.result.data);
						const r = res.result.data
						uniqueArray.map((v, index, it) => {
							v.username = r[index].username
							v.avatar = r[index].avatar
							v.count = 1
							v.time = timestampToDate(v.time)
						})
						console.log(uniqueArray);
						users.value = uniqueArray
						uni.setStorageSync('users', users.value)
					}).catch(err => {
						console.log(err.message);
					})
				
		}).catch((err) => {
			console.log(err.message);
		})
	}


	const getInitData = () => {
		getUserData()
		getHots()
		getHomeTodays()
		getlists()
		getTalking()
	}

	getInitData()
</script>

<style lang="scss" scoped>
	.navigator {
		height: 100rpx;
		background-color: white;
		width: 590rpx;
		border-radius: 70rpx;
		position: fixed;
		bottom: 20rpx;
		left: 60rpx;
		font-size: 22rpx;
		display: flex;
		padding: 0 20rpx;
		align-items: center;

		view {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 163rpx;
			height: 70rpx;
			border-radius: 40rpx;

			image {
				width: 48rpx;
				z-index: 2;
			}

			text {
				margin-left: 10rpx;
				z-index: 2;
			}
		}

		.search {
			image {
				width: 38rpx;
			}
		}

		.message {
			image {
				width: 42rpx;
			}
		}

		.my {
			image {
				width: 29rpx;
			}
		}

		.shadow {
			position: fixed;
			background-color: #FFE7D1;
			left: 75rpx;
			transition: 300ms left ease;
		}
	}
</style>